<?php
namespace app\admin\controller;
//use think\{Controller,Db,Input};//
use think\Controller;
use think\Db;
use think\Input;
use clt\Menu;
use app\admin\model\Users;
use app\admin\model\Messages;
use app\admin\model\Networks;
use app\admin\model\Pops;
use app\admin\model\Orders;
use app\admin\model\Logs;
use app\admin\model\Areas;
class Ajax extends Common{
    public function getRegion(){
        $Region=db("region");
        $map['pid']=input("pid");
        $map['type']=input("type");
        $list=$Region->where($map)->select();
        echo json_encode($list);
    }
    /*获取左菜单*/
    public function menus(){
    	$Menu = new Menu;
    	$Menus=$Menu->getMenus('');
    	return $Menus;
    }
    public function checkPassword($aid=null,$network_id=null,$password=null){
        if(empty($password)){
            return ['code'=>0,'msg'=>lang('Please enter the login password.')];
        }
        if(!Users::isAdmin($this->User_id)){
            return ['code'=>0,'msg'=>lang("You don't have permission to see it.")];
        }
        if(md5($password) != $this->user['pwd']){
            return ['code'=>0,'msg'=>lang('Enter a secret validation error.')];    
        }
        $netword = db('networks')->where('id',$network_id)->find();
        if(!$netword){
            return ['code'=>0,'msg'=>lang('The line does not exist.')];
        }
        
        if($aid == 2){
            $data['aid'] = 2;
            $data['accessID'] = $netword['end_aws_accessID'];
            $data['secrectKey'] = $netword['end_aws_secrectKey'];
        }else{
            $data['aid'] = 1;
            $data['accessID'] = $netword['local_aws_accessID'];
            $data['secrectKey'] = $netword['local_aws_secrectKey'];
        }
        return ['code'=>1,'msg'=>lang('Request success.'),'data'=>$data];
    }
    /*分配工程师*/
    public function fenpei($type=null){
        if($this->request->isPost()){
            $data = $this->request->post();
            $netword = db('networks')->where('id',$data['network_id'])->find();
            if(!$netword){
                return ['code'=>0,'msg'=>lang('The line does not exist.')];
            }
            $data['state'] = $netword['status'];
            $data['status'] = 1; 
            $data['create_time'] = time();
            $data['user_id'] = $this->User_id;
            
            $result = db('network_enginee')->insert($data);
            if($result){
                $netword['noticeType'] = 1;
                $netword['surname'] = Users::getUsername($netword['user_id']);
                $netword['title'] = lang("Hello, the administrator has allocated a route to you. Please cooperate with the configuration:");
                $netword['create_time'] = date('Y-m-d H:i',$netword['create_time']);
                $temp = $this->fetch('message/temp',$netword);
                Messages::Notice($data['enginee_id'],lang('Network line configuration notification'),$temp,1,false);
                
                return ['code'=>1,'msg'=>lang('successful.')];
            }
        }
        return ['code'=>0,'msg'=>lang('Failed.')];
    }
    /*同意开通*/
    public function kaitong($network_id=null,$eng_id=null,$content=null,$isAuto=null){
        if($this->request->isPost()){
            $this->Network = new Networks;
            $nework = $this->Network->get($network_id);
            if(!$nework){
                return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
            }
            $this->Network->startTrans();
            try{
                $ennd = db('network_enginee')->where('id',$eng_id)->find();
                 if(!$ennd){
                    return ['code'=>0,'msg'=>lang('Data does not exist.')];
                }
                if($ennd['enginee_id'] != $this->User_id){
                    return ['code'=>0,'msg'=>lang('sorry, you have no authority.')];
                }
                $data['id'] = $eng_id;
                $data['status'] = 2;
                $data['update_time'] =time();
                $data['content'] = empty($content) ? lang('The engineer has completed the configuration') : $content;
                $returls = db('network_enginee')->update($data);
                /*发送消息*/
                $surname = Users::getUsername($ennd['user_id']);
                $netword['noticeType'] = 1;
                $netword['surname'] = Users::getUsername($nework['user_id']);
                $netword['title'] = '';
                $netword['plan_time'] = $nework['plan_time'];
                $netword['create_time'] = $nework['create_time'];
                $netword['broadband'] = $nework['broadband'];
                $netword['sn'] = $nework['sn'];
                $netword['name'] = $nework['name'];
                $netword['id'] = $nework['id'];
                $temp = $this->fetch('message/temp',$netword);
                $temp = lang('
                    <h4>Hi:'.$surname.'</h4>
                    <p>'.lang('Engineer').','.$this->user['username'].'已完成【'.$nework['name'].'】网络线路配置</p>').$temp;
                Messages::Notice($ennd['user_id'],lang('The engineer has completed the configuration'),$temp,1,false);
                db('network_logs')->insert(
                    array(
                        'user_id'=>$this->User_id,
                        'network_id'=>$network_id,
                        'status'=>$nework->status,
                        'content'=>lang('The engineer decided to open the line'),
                        'create_time'=>time()
                    )
                );
                $productUid = '';
                $isopen = 0;
                $megaport['title'] = $nework['name'];
                $megaport['rateLimit'] = $nework['broadband'];
                $megaport['network_id'] = $nework['id'];
                $megaport['term'] = $nework['daylength'];
                /*自动开通megaport 合作伙伴*/
                if(($nework['type'] == Networks::NETWORK_TYPE_3 || $nework['endtype'] == Networks::NETWORK_TYPE_3) && intval($isAuto) == 1){
                    /*本端*/
                    if($nework['type'] == Networks::NETWORK_TYPE_3 && $nework['country_id'] != Areas::CHINA_ID){
                        $isopen = 1;
                        $megaport['cloud_id'] = $nework['local_cloud_id'];
                        $megaport['data_content'] = $nework['cloud_conter'];
                        $megaport['city_id'] = $nework['city_id'];
                        $megaport['prefixes'] = $nework['local_network'];
                        $megaport['account'] = $nework['local_cloud_userid'];
                        $megaport['authKey'] = $nework['AauthKey'];
                        $megaports = new \clt\Monthly('megaport');
                        $result = $megaports->Buy($megaport);
                        $productUid = $result['productUid'];
                        if(!empty($productUid)){
                            $result = db('netword_products')->insert(['netword_id'=>$nework->id,'productUid'=>$productUid,'type'=>1],true);
                        }
                    }
                    /*对端*/
                    if($nework['endtype'] == Networks::NETWORK_TYPE_3 && $nework['ecountry_id'] != Areas::CHINA_ID){
                         $isopen = 1;
                         $megaport['cloud_id'] = $nework['endcloudid'];
                         $megaport['city_id'] = $nework['ecity_id'];
                         $megaport['prefixes'] = $nework['end_network'];
                         $megaport['account'] = $nework['end_userid'];
                         $megaport['authKey'] = $nework['ZauthKey'];
                         $megaport['data_content'] = $nework['ecloud_conter'];
                         $megaports = new \clt\Monthly('megaport');
                         $result = $megaports->Buy($megaport);
                         $productUid = $result['productUid'];
                         if(!empty($productUid)){
                            $result = db('netword_products')->insert(['netword_id'=>$nework->id,'productUid'=>$productUid,'type'=>2],true);
                         }
                    }
                }
                /*自动开通 VXC*/
                if(($nework['type'] == Networks::NETWORK_TYPE_2 && $nework['endtype'] == Networks::NETWORK_TYPE_2) && intval($isAuto) == 1){
                    /*本段*/
                    if($nework['type'] == Networks::NETWORK_TYPE_2 && $nework['country_id'] != Areas::CHINA_ID && $nework['country_id'] != Areas::HK_ID){
                        $megaport['type'] = 1;
                        $megaport['country_id'] = $nework['country_id'];
                        $megaport['pop_id'] = $nework['pop_id'];
                        $megaports = new \clt\Monthly('megaport');
                        $result = $megaports->BuyVXC($megaport);
                        $productUid = $result['productUid'];
                        if(!empty($productUid)){
                            $result = db('netword_products')->insert(['netword_id'=>$nework->id,'productUid'=>$productUid,'type'=>1],true);
                        }
                    }
                    /*对端*/
                    if($nework['endtype'] == Networks::NETWORK_TYPE_2 && $nework['ecountry_id'] != Areas::CHINA_ID && $nework['ecountry_id'] != Areas::HK_ID){
                        $megaport['type'] = 2;
                        $megaport['pop_id'] = $nework['epop_id'];
                        $megaport['country_id'] = $nework['ecountry_id'];
                        $megaports = new \clt\Monthly('megaport');
                        $result = $megaports->BuyVXC($megaport);
                        $productUid = $result['productUid'];
                        if(!empty($productUid)){
                            $result = db('netword_products')->insert(['netword_id'=>$nework->id,'productUid'=>$productUid,'type'=>2],true);
                        }
                    }
                }
                $this->Network->commit();
                return ['code'=>1,'msg'=>lang('The data was submitted successfully.'),'isopen'=>0];
            }catch(\Exception $e){
                $this->Network->rollback();
                 $message = lang('The operation failed, the unknown error!');
                 if(-404 == $e->getCode()){
                        $message=$e->getMessage();
                }
                Logs::add(['type'=>'Open Network','code'=>$e->getCode(),'message'=>$message]);
                return ['code'=>0,'msg'=>$message];
            }   
            
        }
        
    }
    /*自动开通*/
    public function autoopen($network_id=null){
        if($this->request->isPost()){
            try{
                $this->Network = new Networks;
                $nework = $this->Network->get($network_id);
                if(!$nework){
                    return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
                }
                 /*自动开通megaport*/
                if($nework['type'] == 3 || $nework['endtype'] == 3){
                    $megaport['title'] = $nework['name'];
                    $megaport['rateLimit'] = $nework['broadband'];
                    $megaport['network_id'] = $nework['id'];
                    /*本端*/
                    if($nework['type'] == 3 && $nework['country_id'] != 1){
                        $isopen = 1;
                        $megaport['cloud_id'] = $nework['local_cloud_id'];
                        $megaport['data_content'] = $nework['cloud_conter'];
                        $megaport['city_id'] = $nework['city_id'];
                        $megaport['prefixes'] = $nework['local_network'];
                        $megaport['account'] = $nework['local_cloud_userid'];
                        $megaport['authKey'] = $nework['AauthKey'];
                        $megaports = new \clt\Monthly('megaport');
                        $result = $megaports->Buy($megaport);
                        
                        $productUid = $result['productUid'];
                        if(!empty($productUid)){
                            $result = db('netword_products')->insert(['netword_id'=>$nework->id,'productUid'=>$productUid,'type'=>1],true);
                        }
                    }
                    /*对端*/
                    if($nework['endtype'] == 3 && $nework['ecountry_id'] != 1){
                         $isopen = 1;
                         $megaport['cloud_id'] = $nework['endcloudid'];
                         $megaport['city_id'] = $nework['ecity_id'];
                         $megaport['prefixes'] = $nework['end_network'];
                         $megaport['account'] = $nework['end_userid'];
                         $megaport['authKey'] = $nework['ZauthKey'];
                         $megaport['data_content'] = $nework['ecloud_conter'];
                         $megaports = new \clt\Monthly('megaport');
                         $result = $megaports->Buy($megaport);
                         $productUid = $result['productUid'];
                         if(!empty($productUid)){
                            $result = db('netword_products')->insert(['netword_id'=>$nework->id,'productUid'=>$productUid,'type'=>2],true);
                         }
                    }
                    return ['code'=>1,'msg'=>lang('Successful opening')];
                }  

            }catch(\Exception $e){
                if(-404 == $e->getCode()){
                        return ['code'=>0,'msg'=>$e->getMessage()];
                }
                return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
            } 
        }
        
    }
    /*确认删除*/
    public function confirmdel($network_id=null,$eng_id=null,$content=null){
        if($this->request->isPost()){
            $this->Network = new Networks;
            $nework = $this->Network->get($network_id);
            if(!$nework){
                return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
            }
            try{
                $ennd = db('network_enginee')->where('id',$eng_id)->find();
                 if(!$ennd){
                    return ['code'=>0,'msg'=>lang('Data does not exist.')];
                }
                if($ennd['enginee_id'] != $this->User_id){
                    return ['code'=>0,'msg'=>lang('sorry, you have no authority.')];
                }
                $nework->pre_status = $nework['status'];
                $nework->status = 12;
                $nework->update_time = date('Y-m-d H:i:s',time());
                if($nework->save()){
                    $data['id'] = $eng_id;
                    $data['status'] = 2;
                    $data['update_time'] = time();
                    $data['is_update'] = 1;
                    $data['content'] = empty($content) ? lang('Network line confirmation deletion') : $content;
                    $returls = db('network_enginee')->update($data);
                    /*发送消息*/
                    $surname = Users::getUsername($ennd['user_id']);
                    $netword['noticeType'] = 1;
                    $netword['surname'] = Users::getUsername($nework['user_id']);
                    $netword['title'] = '';
                    $netword['plan_time'] = $nework['plan_time'];
                    $netword['create_time'] = $nework['create_time'];
                    $netword['broadband'] = $nework['broadband'];
                    $netword['sn'] = $nework['sn'];
                    $netword['name'] = $nework['name'];
                    $netword['id'] = $nework['id'];
                    $temp = $this->fetch('message/temp',$netword);
                    $temp = lang('
                        <h4>Hi:'.$surname.'</h4>
                        <p>'.lang('Engineer').', '.$this->user['username'].lang('Deleted').'【'.$nework['name'].'】'.lang('Network Line').'</p>').$temp;
                    Messages::Notice($ennd['user_id'],lang('The network line has been deleted.'),$temp,2,false);//发送给管理员
                    $surname = Users::getUsername($nework['user_id']);
                    $temp = lang('
                        <h4>Hi:'.$surname.'</h4>
                        <p>'.lang('Engineer').','.$this->user['username'].lang('Deleted').'【'.$nework['name'].'】'.lang('Network Line').'</p>').$temp;
                    
                    Messages::Notice($nework->user_id,lang('The network line has been deleted.'),$temp,2,false);//发送给客户
                    db('network_logs')->insert(
                        array(
                            'user_id'=>$this->User_id,
                            'network_id'=>$network_id,
                            'status'=>$nework->status,
                            'content'=>lang('The network line has been deleted.'),
                            'create_time'=>time()
                        )
                    );
                    /*更新流程*/
                    db('network_enginee')->where(['network_id'=>$nework->id,'is_update'=>0])->update(['is_update'=>1,'update_time'=>time()]);
                    //订单订阅
                    Orders::add($nework->id,$this->User_id,3); 
                    return ['code'=>1,'msg'=>lang('The data was submitted successfully.')];
                }
                return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
            }catch(\Exception $e){
                $nework->rollback();
                return ['code'=>0,'msg'=>lang('The operation failed, the unknown error!')];
                
            }
            
        }
    }
    /*工程师反馈*/
    public function rebackcontent($network_id=null,$status=null){
        if($this->request->isPost()){
            $data = $this->request->post();
            $ennd = db('network_enginee')->where('id',$data['id'])->find();
            if(!$ennd){
                return ['code'=>0,'msg'=>lang('Data does not exist.')];
            }
            if($ennd['enginee_id'] != $this->User_id){
                return ['code'=>0,'msg'=>lang('sorry, you have no authority.')];
            }
            if(empty($data['content'])){
                return ['code'=>0,'msg'=>lang('Please enter the feedback content.')];
            }
            $this->Network = new Networks;
            $nework = $this->Network->get($network_id);
            if(!$nework){
                return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
            }
            $data['status'] = (int)$status == 3 ? 3 : 2;
            $data['is_update'] = 1;
            $data['update_time'] = time();
            if(db('network_enginee')->update($data)){
                $surname = Users::getUsername($ennd['user_id']);
                $netword['noticeType'] = 1;
                $netword['surname'] = Users::getUsername($nework['user_id']);
                $netword['title'] = '';
                $netword['plan_time'] = $nework['plan_time'];
                $netword['create_time'] = $nework['create_time'];
                $netword['broadband'] = $nework['broadband'];
                $netword['sn'] = $nework['sn'];
                $netword['name'] = $nework['name'];
                $netword['id'] = $nework['id'];
                $temp = $this->fetch('message/temp',$netword);
                $temp = lang('
                    <h4>Hi:'.$surname.'</h4>
                    <p>工程师，'.$this->user['username'].'已反馈【'.$nework['name'].'】网络线路配置信息，反馈内容:</p>
                    <p>'.$data['content'].'</p>
                    ').$temp;
                Messages::Notice($ennd['user_id'],lang('The engineer has completed the configuration'),$temp,1,false);
                return ['code'=>1,'msg'=>lang('successful.')];
            }            
            return ['code'=>0,'msg'=>lang('Failed.')];
            
        }
    }
    public function updateEng($id=null){
        $data = $this->request->post();
        $ennd = db('network_enginee')->where('id',$id)->find();
        if(!$ennd){
            return ['code'=>0,'msg'=>lang('Data does not exist.')];
        }
        if($ennd['enginee_id'] == $data['enginee_id']){
            return ['code'=>0,'msg'=>lang("You can't repeat it.")];
        }
        $this->Network = new Networks;
        $nework = $this->Network->get($ennd['network_id']);
        if(!$nework){
            return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
        }
        $data['id'] = $id;
        $data['enginee_id'] = $data['enginee_id'];
        $surname = Users::getUsername($ennd['enginee_id']);
        if(db('network_enginee')->update($data)){
                $netword['noticeType'] = 1;
                $netword['surname'] = Users::getUsername($data['enginee_id']);
                $netword['title'] = lang('Hi:'.$surname.',管理员已经取消了你配置:'.$nework['name'].'线路权限');
                $netword['create_time'] = $nework['create_time'];
                $netword['name'] = $nework->name;
                $netword['plan_time'] = $nework->plan_time;
                $netword['id'] = $nework->id;
                $temp = $this->fetch('message/temp',$netword);
                Messages::Notice($ennd['enginee_id'],lang('Network line configuration notification'),$temp,1,false);
                $netword['title'] = lang("Hello, the administrator has allocated a route to you. Please cooperate with the configuration:");
                $temp = $this->fetch('message/temp',$netword);
                Messages::Notice($data['enginee_id'],lang('Network line configuration notification'),$temp,1,false);
                return ['code'=>1,'msg'=>lang('successful.')];
        }
        return ['code'=>0,'msg'=>lang('Failed.')];
    }
    public function updateField($nework_id=null){
        $this->Network = new Networks;
        $network =  $this->Network->get($nework_id);
        if(!$network){
            return ['code'=>0,'msg'=>lang('Network lines do not exist.')];
        }
        $data['value'] = str_replace("--", '', $data['value']);
        $data = $this->request->post();
        if($data['field'] == 'local_network' || $data['field'] == 'end_network' ){
            if(!empty($data['value']) && !valid_ip($data['value'])){
                return ['code'=>0,'msg'=>lang('Network address format is not correct.')];
            }
        }
        /*时间处理*/
        if('appro_time' == $data['field'] || 'enddate' == $data['field']){
            $data['value'] = strtotime($data['value']);
        }
        if($data['value'] == $network[$data['field']] || $data['value']=='--'){
            return ['code'=>1,'msg'=>lang('successful.')];
        }
        $network[$data['field']] = $data['value'];
        $network['update_time'] =date('Y-m-d H:i:s', time());
        if($network->save()){
            return ['code'=>1,'msg'=>lang('successful.')];
        }
        return ['code'=>0,'msg'=>lang('Failed.')];
    }
    /*获取资源*/
    public function getsource($type=null){
        if($type == 2){
            $pops = Pops::getPOPCountryCitys();
            return ['code'=>1,'msg'=>lang('Set up successfully.'),'items'=>$pops];
        }
    }
    public function getUsage($network_id=null,$hours=null){
        $megaports = new \clt\Monthly('megaport');
        $productUid = db('netword_products')->where(['netword_id'=>$network_id])->value('productUid');
        if(!empty($productUid)){
            $hours = intval($hours) > 0 ? $hours : 12;
            $timd = strtotime(date('Y-m-d',time()).date('H',time()).":00");
            $map = ['productIdOrUid'=>$productUid,'to'=>$timd*1000,'from'=>($timd-$hours*3600)*1000];
            $result = $megaports->getUsage($map);
            $date = [];
            $result = json_decode($result,true);
            if($result && isset($result['data']) && isset($result['data']['in_mbps'])){
                foreach($result['data']['in_mbps'] as $k=>$v){
                    $date[] = date('Y-m-d H:i',($map['from']/1000)+$k*5*60);
                }
                $result['data']['datetime'] = $date;
                //$result['data']['max']=max($result['data']['in_mbps']);
                return $result;
            }
        }
        return $result = array(
            'data'=>array('datetime'=>[],'in_mbps'=>[],'out_mbps'=>[],'name'=>db('networks')->where(['id'=>$network_id])->value('name')),
            'message'=>'error',
        );
    }
}